package com.itheima.health.userdetailservice;

import com.itheima.health.pojo.Permission;
import com.itheima.health.service.UserService;
import com.itheima.health.vo.RoleVO;
import com.itheima.health.vo.UserVO;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class MyUserDetailServiceImpl implements UserDetailsService {

    @Reference
    private UserService userService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //    根据用户账号 查询 角色和权限关键字  账号 密码  权限和角色关键字
           UserVO userFormDB = userService.findUserInfoByUsername(username);
//           UserVO   角色信息+角色对应权限信息
        if(userFormDB==null){
            return  null;
        }
        List<GrantedAuthority> list = new ArrayList<GrantedAuthority>();
        //  当前用户所有的角色和权限 关键字
        List<RoleVO> roleVOList = userFormDB.getRoleVOList();
        for (RoleVO roleVO : roleVOList) {
            list.add(new SimpleGrantedAuthority(roleVO.getKeyword()));
            List<Permission> permissionsList = roleVO.getPermissionsList();
            for (Permission permission : permissionsList) {
                list.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }
        return  new User(username,userFormDB.getPassword(),list);
    }
}
